import axios from 'axios'

// 表单序列化
export const serialize = (data) => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}

/**
 * 下载exc文件
 * @param data 文件流（或者下载的url）
 * @param filename 文件名
 * @param isUrl data是否url地址，默认否
 */
export function downloadFile(data, filename = '文件.xls', isUrl = false) {
  function download() {
    // const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
    const blob = new Blob([data], { type: 'application/octet-stream' })
    if ('download' in document.createElement('a')) {
      const aNode = document.createElement('a')
      const url = isUrl ? data : window.URL.createObjectURL(blob)
      aNode.download = filename
      aNode.style.display = 'none'
      aNode.href = url
      isUrl && (aNode.target = '_blank')
      document.body.appendChild(aNode)
      aNode.click()
      document.body.removeChild(aNode)
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    } else {
    // IE 10+
      (window.navigator).msSaveBlob(blob, filename)
    }
  }
  if (!isUrl) return download()
  axios({ url: data, responseType: 'blob' }).then(res => {
    data = res.data
    isUrl = false
  }).finally(download)
}

/**
 * 下载文件
 * @deprecated 已废弃，请使用 `downloadFile` 替代
 */
export const dowloadExc = downloadFile
